package cn.java.dao.impl;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;

public class UserDaoImpl {
	
	private SqlSession session=null;
	
	@Before
	public void Init() throws IOException{
		//1.启动mybatis框架 
		//SqlSession <---------SqlSessionFactory <---------SqlSessionFactoryBuilder
		SqlSessionFactoryBuilder sfb=new SqlSessionFactoryBuilder();
		//将mybatis.xml文件转化为输入流
		InputStream inputStream= Resources.getResourceAsStream("mybatis.xml");
		SqlSessionFactory ssf=sfb.build(inputStream);
		session=ssf.openSession();
	}
	
	
	@Test
	public void getUserByCondition() throws IOException{
		//创建一个Map来封装参数
		Map<String, Object> paramMap=new HashMap<String,Object>();
		paramMap.put("username", "王二麻子");
		paramMap.put("pwd", "123");
		//调用局部配置文件中的sql语句(namespace下id为getUserByCondition的select)
		Map<String, Object> userMap= session.selectOne("cn.java.dao.impl.UserDaoImpl.getUserByCondition",paramMap);
		System.out.println(userMap);
	}
	
	@Test
	public void getUserByCondition2() throws IOException{
		//创建一个Map来封装参数
		
		//调用局部配置文件中的sql语句(namespace下id为getUserByCondition2的select)
		List<Map<String, Object>> userList= session.selectList("cn.java.dao.impl.UserDaoImpl.getUserByCondition2");
		System.out.println(userList);
	}
	
	/**
	 * 动态查询
	 */
	@Test
	public void selectComByDynamic(){
		Map<String, Object> paramMap=new HashMap<String,Object>();
		paramMap.put("computerName", "ddd");
		paramMap.put("brand", "联想");
		paramMap.put("runMem", 8);
		paramMap.put("price", 6500);
		List<Map<String, Object>> computerList=session.selectList("cn.java.dao.impl.UserDaoImpl.selectComByDynamic", paramMap);
		for (Map<String, Object> map : computerList) {
			System.out.println(map);
		}
	}
	
	@Test
	public void IfElse(){
		Map<String, Object> paramMap=new HashMap<String,Object>();
		paramMap.put("flag", 2);
		List<Map<String, Object>> computerList=session.selectList("cn.java.dao.impl.UserDaoImpl.IfElse", paramMap);
		for (Map<String, Object> map : computerList) {
			System.out.println(map);
		}
	}
	
	@Test
	public void dynamicUpdate(){
		Map<String, Object> paramMap=new HashMap<String,Object>();
		//paramMap.put("computerName", "外星人");
		//paramMap.put("brand", "联想");
		//paramMap.put("runMem", 8);
		//paramMap.put("price", 6500);
		//paramMap.put("id", 2L);
		int i=session.update("cn.java.dao.impl.UserDaoImpl.dynamicUpdate", paramMap);
		session.commit();
		System.out.println(i);
	}
	
}
